package com.example.module_car.view

import android.app.AlertDialog
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.example.module_car.R
import com.example.module_car.adapter.CarPaymentsAdapter
import com.example.module_car.databinding.ActivityCarBinding
import com.example.module_car.vm.CarViewModel
import com.yuwei.base.BaseActivity
import com.yuwei.common.path.RouterPath
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
@Route(path = RouterPath.CAR)
class CarActivity : BaseActivity<ActivityCarBinding, CarViewModel>() {
    val carPaymentsAdapter = CarPaymentsAdapter()
    override fun initView() {
        binding.vehicleRv.adapter = carPaymentsAdapter
        binding.vehicleRv.layoutManager = LinearLayoutManager(this)
        vm.getCarPayments()
        carPaymentsAdapter.addChildClickViewIds(R.id.vehicle_edit,R.id.vehicle_delete)
        carPaymentsAdapter.setOnItemChildClickListener { adapter, view, position ->
            when(view.id){
                R.id.vehicle_edit ->{
                    ARouter.getInstance().build(RouterPath.CAR_SPACES).navigation()
                }
                R.id.vehicle_delete ->{
                    AlertDialog.Builder(this)
                        .setTitle("删除提醒！")
                        .setMessage("确定要删除车辆信息吗?")
                        .setPositiveButton("确定"){dialog,_ ->
                            vm.deleteCar(carPaymentsAdapter.data[position].id)
                            dialog.dismiss()
                        }
                        .setNegativeButton("取消"){dialog,_ ->
                            dialog.dismiss()
                        }
                        .create()
                        .show()
                    return@setOnItemChildClickListener
                }
            }

        }
        binding.vehicleAddBtn.setOnClickListener {
            ARouter.getInstance().build(RouterPath.ADD_CAR).navigation()
        }
        binding.vehicleBack.setOnClickListener {
            finish()
        }
    }

    override fun initData() {
        vm.getCarPaymentsSuccess.observe(this){
            carPaymentsAdapter.data.clear()
            carPaymentsAdapter.data.addAll(it.reversed())
            carPaymentsAdapter.notifyDataSetChanged()
        }

        vm.getDeleteCarSuccess.observe(this){
            ToastUtils.showShort("删除成功")
            carPaymentsAdapter.data.clear()
            vm.getCarPayments()
            carPaymentsAdapter.notifyDataSetChanged()
        }
    }

    override fun onResume() {
        super.onResume()
        vm.getCarPayments()
        carPaymentsAdapter.notifyDataSetChanged()
    }
}